<template>
  <div>
    <Header :isGoBack="false">
      <template v-slot:right>
        <el-dropdown
          style="margin-right: 20px;"
          trigger="click"
          @command="handleCommand"
        >
          <span class="el-dropdown-link">
            换单词<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="item in wordList"
              :key="item.id"
              :disabled="item.id == letterData.id"
              :command="item"
              >{{ item.content }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <div class="btn" @click="$goRouter('naturalSpellCenter', $route.query)">
          关闭
          <img class="ml5" src="@/assets/img/close-circle.png" alt="" />
        </div>
      </template>
    </Header>
    <div class="quick-test question-practice spell-test">
      <div class="flex-space-be question-practice-container w1200">
        <div class="question-left question-container">
          <div
            class="question-com"
            v-for="(question, index) in questionList"
            :key="question.id"
            v-show="index == nowIndex"
          >
            <div class="question-header flex-space-be">
              <div class="left-type">
                {{ questionType[question.type] }}
              </div>
              <span class="number">
                <b>{{ nowIndex + 1 }}</b
                >/ {{ questionList.length }}
              </span>
              <!-- <span v-if="question.type == 1">
                温馨提示：四个选项分别对应快捷键1/2/3/4，按“Enter”进入下一题。
              </span>
              <span v-else> 温馨提示：按“Enter”进入下一题。 </span> -->
            </div>
            <div class="question-box question-left-container">
              <SpellQuestion
                :key="spellStudyBoxKey"
                :question="question"
                :isAnswer="isSubmit"
                ref="question"
                @audioRecord="
                  (formData, blob) => {
                    audioRecord(formData, blob, index);
                  }
                "
              ></SpellQuestion>
            </div>
          </div>
        </div>
        <div class="question-right-spell">
          <div class="question-right">
            <div class="question-right-header">
              <h4>题目序号</h4>
            </div>
            <div class="question-right-container scrollbar">
              <div class="list-num">
                <div
                  class="list-num-item click"
                  :class="[
                    isSubmit && question.isTrue ? 'right-item' : '',
                    isSubmit && isAnswered(question) && !question.isTrue
                      ? 'wrong-item'
                      : '',
                    !isSubmit && isAnswered(question) ? 'answered-item' : '',
                    index == nowIndex ? 'checked-item' : '',
                  ]"
                  v-for="(question, index) in questionList"
                  :key="index"
                  @click="checkNum(index)"
                >
                  {{ index + 1 }}
                </div>
              </div>
            </div>
            <div class="right-container-note">
              <div class="note-item note-item-checked">
                <span class="color"></span>
                <span class="text">选择</span>
              </div>
              <div class="note-item note-item-true" v-if="isSubmit">
                <span class="color"></span>
                <span class="text">正确</span>
              </div>
              <div class="note-item note-item-false" v-if="isSubmit">
                <span class="color"></span>
                <span class="text">错误</span>
              </div>
              <div class="note-item note-item-answered" v-if="!isSubmit">
                <span class="color"></span>
                <span class="text">已答</span>
              </div>
              <div class="note-item">
                <span class="color"></span>
                <span class="text">未答</span>
              </div>
            </div>
          </div>
          <div class="right-btn" v-if="!isSubmit">
            <el-button
              class="button button-bg-primary"
              v-if="nowIndex == questionList.length - 1"
              @click="submitPaper"
            >
              提交答案
            </el-button>
            <el-button
              class="button button-bg-primary"
              v-else
              @click="checkNum(nowIndex + 1)"
            >
              下一个
            </el-button>
          </div>
          <div class="right-btn" v-if="isSubmit">
            <el-button
              class="button button-bg-primary"
              @click="goNextSpell"
              v-if="passNumber >= 4 && this.nextData"
            >
              学习下一个
            </el-button>
            <el-button
              v-else
              class="button button-bg-primary"
              @click="$goRouter('naturalSpellCenter', $route.query)"
            >
              返回学习中心
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from "@/components/Header";
import SpellQuestion from "./SpellQuestion.vue";
import {
  getSpellQuestion,
  postTestSpellVoice,
  postTestQuestion,
  getNaturalSpellList,
} from "@/api/naturalSpell";
export default {
  watch: {
    "$route.query.checkedTypeId"(newVal, oldVal) {
      this.spellId = newVal;
      if (localStorage.getItem("spellCheckedData")) {
        this.letterData = JSON.parse(localStorage.getItem("spellCheckedData"));
      }
      this.title = this.$route.query.checkedTitle;
      this.getSpellQuestion();
      this.getCatalogListFlatten();
      this.spellStudyBoxKey += 1;
    },
    immediate: true,
  },
  data() {
    return {
      spellStudyBoxKey: 1,
      letterData: null,
      wordList: [],
      checkedBookData: {},
      questionType: {
        1: "单选题",
        2: "填空题",
        3: "音频题",
      },
      isSubmit: false,
      nowIndex: 0,
      questionList: [],
      spellId: null,
      title: "",
      passNumber: 0,
      catalogList_flatten: [],
      nextData: null,
    };
  },
  computed: {},
  methods: {
    handleCommand(item) {
      // this.content = item.content
      // Object.assign(this.$data, this.$options.data())
      this.questionList=[]
      this.isSubmit=false
      let { checkedTitle, source } = this.$route.query;
      localStorage.setItem("spellCheckedData", JSON.stringify(item));
      this.$goRouter("spellTestAfterStudy", {
        checkedTypeId: item.id,
        checkedTitle,
        source,
      });
      this.checkNum(0)
    },
    isAnswered(question) {
      if (question.type == 3) {
        if (!(question.score || question.score === 0)) {
          return false;
        }
      } else {
        if (
          !question.stuAnswer ||
          question.stuAnswer.length == 0 ||
          question.stuAnswer.every((item) => {
            return !(item || item === 0);
          })
        ) {
          return false;
        }
      }
      return true;
    },
    checkNum(index) {
      this.nowIndex = index;
      if (!this.isSubmit) {
        this.$refs["question"].forEach((item) => {
          item.pauseRecord();
        });
        this.getQuestionAnswer();
      }
    },
    audioRecord(formData, blob, index) {
      let question = this.questionList[index];
      formData.append("question_id", question.question_id);
      formData.append("content", question.title);
      formData.append("id", question.id);
      postTestSpellVoice(formData).then((res) => {
        if (res.code == 200) {
          let resultData = res.data[0];
          this.$set(question, "isTrue", resultData.is_true);
          this.$set(question, "score", resultData.evaluate.result.overall);
          this.$set(
            question,
            "result",
            resultData.evaluate.result.details.word[0]
          );
          this.$set(question, "fileData", window.URL.createObjectURL(blob));
        }
      });
    },
    getSpellQuestion() {
      let params = {
        elementId: this.spellId,
      };
      getSpellQuestion(params).then((res) => {
        if (res.code == 200) {
          let questionList = res.data;
          questionList.forEach((question) => {
            question.stuAnswer = [];
            question.oldTitle = question.title;
            let newTitle = question.title;
            if (question.type == 2) {
              let index = 1;
              let pos = newTitle.indexOf("_____");
              while (pos !== -1) {
                newTitle = newTitle.replace(
                  /_{5}/,
                  ` <input class='question-input' maxlength="5" autocomplete="off" id='input-${question.question_id}-${index}' onpaste = "return false";></input> `
                );
                index++;
                pos = newTitle.indexOf("_____");
              }
              question.inputNum = index - 1;
            }
            question.title = newTitle;
          });
          this.questionList = questionList;
          if (this.questionList.length == 0) {
            this.$alert("暂无试题", "提示", {
              confirmButtonText: "确定",
              callback: () => {
                this.$goRouter("naturalSpellCenter", this.$route.query);
              },
            });
          }
        }
      });
    },
    getQuestionAnswer() {
      this.questionList.forEach((question) => {
        if (question.type == 2) {
          question.stuAnswer = [];
          for (let i = 1; i <= question.inputNum; i++) {
            let inputDom = document.getElementById(
              `input-${question.question_id}-${i}`
            );
            question.stuAnswer.push(inputDom.value.trim());
          }
        }
      });
    },
    submitPaper() {
      let number = 0;
      this.getQuestionAnswer();
      this.questionList.forEach((question) => {
        if (question.type == 3) {
          if (!(question.score || question.score === 0)) {
            number++;
          }
        } else {
          if (
            !question.stuAnswer ||
            question.stuAnswer.length == 0 ||
            question.stuAnswer.every((item) => {
              return !(item || item === 0);
            })
          ) {
            number++;
          }
        }
      });
      this.$confirm(
        `${number > 0 ? "还有" + number + "道题未答，" : ""}
        是否检查完毕，确认提交？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }
      )
        .then(() => {
          this.postPaper();
        })
        .catch(() => {
          return false;
        });
    },
    postPaper() {
      let data = {
        list: this.questionList
          .filter((item) => {
            return item.type != 3;
          })
          .map((item) => {
            console.log(item);
            return {
              question_id: item.question_id,
              id: item.id,
              type: item.type,
              student_answer: item.stuAnswer.map((answer) => {
                if (item.type == 1) {
                  return {
                    answer_id: answer,
                  };
                }
                if (item.type == 2) {
                  return {
                    answer: answer,
                  };
                }
              }),
            };
          }),
      };
      if (data.list.length == 0) {
        this.setAnswerData();
        return;
      }
      postTestQuestion(data).then((res) => {
        if (res.code == 200) {
          this.questionList.forEach((item1) => {
            if (item1.type == 3) {
              item1.trueAnswer = [];
            } else {
              item1.title = item1.oldTitle;
              item1.isTrue = false;
              item1.trueAnswer = [];
              item1.studentAnswer = [];
            }
            res.data.forEach((item2) => {
              if (item1.question_id == item2.question_id) {
                item1.isTrue = item2.is_true;
                item1.trueAnswer = item2.answers.filter((item) => {
                  return item.is_true;
                });
                item1.studentAnswer = item2.spell_student_answer;
              }
            });
          });
          this.setAnswerData();
        }
      });
    },
    setAnswerData() {
      this.isSubmit = true;
      this.passNumber = this.questionList.reduce((pre, item) => {
        return (pre += item.isTrue ? 1 : 0);
      }, 0);
      let index = this.catalogList_flatten.findIndex((item) => {
        return item.id == this.spellId;
      });
      let nowData = null;
      if (index != -1) {
        nowData = this.catalogList_flatten[index];
      }
      if (index + 1 < this.catalogList_flatten.length) {
        this.nextData = this.catalogList_flatten[index + 1];
      }
      //   恭喜你已掌握当前a单词的发音，点击按钮去学习下一个吧
      if (this.passNumber >= 4) {
        this.$confirm(
          `恭喜你已掌握当前${nowData ? nowData.content : ""}单词的发音 ${
            this.nextData ? "，点击按钮去学习下一个吧" : ""
          } `,
          "提示",
          {
            confirmButtonText: `${this.nextData ? "下一个" : "返回学习中心"}`,
            cancelButtonText: "查看试题",
            closeOnClickModal: false,
            closeOnPressEscape: false,
          }
        )
          .then(() => {
            this.goNextSpell();
          })
          .catch(() => {
            return false;
          });
      }
    },
    goNextSpell() {
      if (this.nextData) {
        localStorage.setItem("spellCheckedData", JSON.stringify(this.nextData));
        this.$router.push({
          name: "spellStudy",
          query: {
            checkedTypeId: this.nextData.id,
            checkedTitle: `${this.nextData.content_1} - ${this.nextData.content_2} - ${this.nextData.content}`,
            source: this.nextData.source,
          },
        });
      } else {
        this.$goRouter("naturalSpellCenter", this.$route.query);
      }
    },
    getCatalogListFlatten() {
      let catalogList_flatten = JSON.parse(
        localStorage.getItem("catalogList_flatten")
      );
      if (catalogList_flatten) {
        this.catalogList_flatten = catalogList_flatten;
      } else {
        this.getNaturalSpellList();
      }
    },
    getNaturalSpellList() {
      return new Promise((reslove, reject) => {
        getNaturalSpellList()
          .then((res) => {
            if (res.code == 200) {
              this.setIsSpellData(res.data);
              this.catalogList_flatten = this.flatten(res.data);
              reslove();
            }
            reject();
          })
          .catch(() => {
            reject();
          });
      });
    },
    setIsSpellData(list) {
      list.forEach((item1) => {
        item1.object_list &&
          item1.object_list.forEach((item2) => {
            item2.object_list &&
              item2.object_list.forEach((item3) => {
                item3.id_1 = item1.id;
                item3.id_2 = item2.id;
                item3.content_1 = item1.content;
                item3.content_2 = item2.content;
              });
          });
      });
    },
  },
  created() {
    this.wordList = JSON.parse(localStorage.getItem("spellCheckeWordlist"));
    this.letterData = JSON.parse(localStorage.getItem("spellCheckedData"));
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.title = this.$route.query.checkedTitle;
    this.spellId = Number(this.$route.query.checkedTypeId);
    this.getSpellQuestion();
    this.getCatalogListFlatten();
  },
  components: {
    Header,
    SpellQuestion,
  },
};
</script>
